import React, { useEffect, useRef, useState } from "react";
import { Button, Toast } from "antd-mobile";
import { checkENV, isValidArr } from "@/utils";
import { NotiComp, PopComp, PopLightComp } from "@/components/common";
import useGame from "@/components/pages/game/car/stores/useGame";
import requewt from "@/utils/requewt";
import { API, MINI_P_ID, MINI_P_PATH, REDIRECT_COVER, REDIRECT_TITLE, REDIRECT_URL } from "@/config";
import callFeedback from "@/components/common/modalFeedback";
import { triggerShare } from "@/components/pages/game/car/utils";

const pageName = "game.v.end";
const klassName = pageName.replace(/\./g, '-');

export default function VReadyComp({children, content, header, id, handler}) {
  let distance = useGame(state => state.distance)
  let passed = useGame(state => state.passed)
  const [score, setScore] = useState(0)

  useEffect(() => {
    (async () => {
      const resolve = await checkENV();
      if (resolve === `mini`) {
        const data = {
          title: REDIRECT_TITLE, // 分享标题
          path: `/pagesPublic/h5/detailH5?jumpDataVale=${encodeURIComponent(REDIRECT_URL)}`,
          imageUrl: REDIRECT_COVER
        }
        // alert(JSON.stringify(data))
        wx.miniProgram.postMessage({data})
      }


      // Toast.show({icon: `loading`, content: `提交数据中`})
      // const options = {
      //   method: `POST`,
      //   headers: {"Content-Type": `multipart/form-data`},
      //   body: {id: id, mileage: (distance / 100).toFixed(2)}
      // }
      // const resp = await requewt(API.task.complete, options);
      // Toast.clear();
      // if (resp?.error_code !== 0 || resp?.msg !== `ok`) {
      //   callFeedback({
      //     title: <div dangerouslySetInnerHTML={{__html: resp?.msg || `失败!`}}>
      //     </div>
      //   })
      //   return
      // }
      // setScore(resp?.data?.score)
    })()
  }, [])

  const comHandler = {
    restart: () => {
      window.location.reload()
    },
    share: async () => {
      const env = checkENV();
      if (env === `mini`) await triggerShare()
      else {
        const json = {
          shareTitle: REDIRECT_TITLE,
          shareUrl: REDIRECT_URL,
          shareImg: REDIRECT_COVER,
          shareDesc: ``,
          shareType: "3",
          isImg: "0",

          isMiniProgram: "1",
          userName: MINI_P_ID,
          path: MINI_P_PATH,
          miniprogramType: 0,
        }
        try {
          // 菜单分享
          window.QYApp?.shareTo(JSON.stringify(json), 'shareCallBack')
        } catch (error) {
          Toast.show({content: `分享失败`})
        }
      }
    },
    link: async () => {
      const resolve = checkENV();
      if (resolve === `mini`) {
        try {
          wx.miniProgram.navigateTo({url: '/pages/index/index?current=2'})
        } catch (e) {

        }
      } else if (resolve === `app`) {
        window.location.href = `https://head.uni.changan.com.cn/order/#/orderUNI/index?id=18`
      }

      await requewt(API.task.record, {method: `POST`});
    }
  }

  return (
    <div className={`cp-${klassName}`}>
      <div className="inner">
        <div className="cp-header">
          <img src="https://yinli-qixi-run.varwey.com/2023/230318-changan-kv-game/img/v-title.png" alt="" />
        </div>

        <div className="content">
          <NotiComp
            header={
              <div className="inner">
                <div className="title text-center">游戏结束</div>
              </div>
            }
            content={
              <>
                你在本次智电疾速旅程中 <br />
                仅用<font>{(passed / 1000).toFixed(0)}</font>秒
                疾速前进了<font>{(distance / 100).toFixed(2)}</font>里程<br />
                共获得了<font>{score}</font>积分奖励
              </>
            }
            actions={false}
          />

        </div>

        <div className="footer">
          <Button className={`act-btn act-btn-diamond`} onClick={comHandler.restart}>重新开始</Button>
          <Button className={`act-btn act-btn-diamond`} onClick={handler.switch}>返回首页</Button>
        </div>

        <PopLightComp>
          <div onClick={comHandler.link}>
            <img className="thumb"
                 src="https://yinli-qixi-run.varwey.com/2023/230318-changan-kv-game/img/v-banner.jpg" alt="" />
          </div>
          <div className="title">
            点击探索更多福利
          </div>
        </PopLightComp>
      </div>
    </div>
  )
}

